# -*- coding: utf-8 -*-
"""
说明：gds系统酒店相关服务客户端方法
文档：http://gitlab.breadtrip.com:1280/liyangliang/hotelsvc/blob/develop/docs/ihotels.md
"""

import json
import datetime
import requests

from flask import current_app


def tomorrow(base=None):
    if not base:
        base = datetime.date.today()
    return base + datetime.timedelta(days=1)


def default_check_in_out_date():
    check_in_date = tomorrow()
    check_out_date = tomorrow(check_in_date)

    fmt = '%Y-%m-%d'
    return check_in_date.strftime(fmt), check_out_date.strftime(fmt)


class GDSClient(object):
    def __init__(self, host=current_app.config['HOTEL_SERVICE_HOST'], port=current_app.config['HOTEL_SERVICE_PORT']):
        self.base_url = "http://%s:%d" % (host, port)

        self._hotel_regions_url = self._make_url('/ihotel/regions')
        self._hotel_list_url = self._make_url('/ihotel/list')
        self._hotel_detail_url = self._make_url('/ihotel/detail')
        self._order_create_url = self._make_url('/order/create')
        self._order_get_url = self._make_url('/order/get')
        self._order_list_url = self._make_url('/order/list')
        self._order_canceltips_url = self._make_url('/order/canceltips')
        self._order_cancel_url = self._make_url('/order/cancel')
        self._order_payment_callback_url = self._make_url('/order/payment/callback')
        self._hotel_by_place_url = self._make_url('/ihotel/byplace')
        self._hot_city_url = self._make_url('/ihotel/hot_cities')
        self._search_region_url = self._make_url('/ihotel/regions')
        self._order_identity_update = self._make_url('/order/owner/update')
        self._session = requests.Session()

    def _make_url(self, path):
        """
        构建基础的url格式
        """
        return "%s%s" % (self.base_url, path)

    def _resp_json(self, request):
        """
        1 校验 http 请求返回的 status_code
        2 不校验 json 返回值的 code(调用方需要code信息)
        """
        prepared_request = request.prepare()
        response = self._session.send(prepared_request)
        # print '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> GDS API'
        # list_content = [
        #     datetime.datetime.now().strftime('[%Y-%m-%d %H:%M:%S]'),
        #     str(response.elapsed),
        #     str(response.status_code),
        #     prepared_request.method,
        #     prepared_request.url,
        #     request.headers,
        #     request.params,
        #     request.data,
        # ]
        # log_content = ''.join(map(lambda x: '[ %s ]' % x, list_content))
        # print '[GDS API][request]', request.method, request, prepared_request
        print '[gds request url] ', prepared_request.url
        # print '[headers]', request.headers
        # print '[params]', request.params
        # print '[data]', request.data
        # print '[GDS API][response]', request.method, response
        # print '[status_code]', response.status_code
        # if response.status_code == 200:
        #     print json.JSONEncoder(indent=4).encode(response.json())
        # else:
        #     print response.text
        # print '[GDS API][log]'
        # print log_content
        # print '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> GDS API'
        if response.status_code == 200:
            ret = response.json()
            return ret
        else:
            print response.status_code

    def _resp_json_data(self, request):
        """
        1 校验 http 请求返回的 status_code
        2 校验 json 返回值的 code(调用方不需要code信息)
        """
        ret = self._resp_json(request)
        if ret['code'] == 0:
            return ret['data']
        else:
            print '[GDS API][Error][code != 0]'
            print json.JSONEncoder(indent=4).encode(ret)
            print ret['message']
            return {}

    def region_list(self):
        """
        获取支持的全部区域信息列表
        """
        args = {}
        request = requests.Request(method='GET',
                                   url=self._hotel_regions_url,
                                   params=args)
        return self._resp_json_data(request)

    def hot_city_list(self):
        """
        查询热门城市列表
        """
        request = requests.Request(method='GET',
                                   url=self._hot_city_url)
        return self._resp_json_data(request)

    def hotel_list(self, **kwargs):
        """
        根据查询条件获取酒店列表信息
        """

        if 'checkInDate' not in kwargs:
            checkin_date, checkout_date = default_check_in_out_date()
            kwargs.update({'checkInDate': checkin_date, 'checkOutDate': checkout_date})

        request = requests.Request(method='GET',
                                   url=self._hotel_list_url,
                                   params=kwargs)
        return self._resp_json_data(request)

    def hotel_detail(self, **kwargs):
        """
        获取酒店详细信息
        """

        if 'checkInDate' not in kwargs:
            checkin_date, checkout_date = default_check_in_out_date()
            kwargs.update({'checkInDate': checkin_date, 'checkOutDate': checkout_date})

        rooms_num = 1
        if 'rooms' not in kwargs:
            default = [{
                "numberOfAdults": 1,
                "childAges": ""
            }]
            rooms = json.dumps(default)
            kwargs.update({'rooms': rooms})
        else:
            rooms = json.loads(kwargs['rooms'])
            rooms_num = len(rooms)

        request = requests.Request(method='GET',
                                   url=self._hotel_detail_url,
                                   params=kwargs)
        data = self._resp_json_data(request)
        if data:
            data.update({'checkInDate': kwargs['checkInDate'], 'checkOutDate': kwargs['checkOutDate'], 'rooms_num': rooms_num})
        return data

    def order_create(self, **kwargs):
        """
        创建订单
        """
        args = {}
        args.update(**kwargs)
        args.update(source='vacation')
        request = requests.Request(method='POST',
                                   url=self._order_create_url,
                                   data=args)
        return self._resp_json(request)

    def order_get(self, **kwargs):
        """
        查询订单
        """
        args = {}
        args.update(**kwargs)
        request = requests.Request(method='GET',
                                   url=self._order_get_url,
                                   params=args)
        return self._resp_json_data(request)

    def order_list(self, **kwargs):
        """
        获取订单列表
        """
        args = {}
        args.update(**kwargs)
        request = requests.Request(method='GET',
                                   url=self._order_list_url,
                                   params=args)
        return self._resp_json_data(request)

    def order_cancel(self, **kwargs):
        """
        取消订单
        """
        args = {}
        args.update(**kwargs)
        request = requests.Request(method='POST',
                                   url=self._order_cancel_url,
                                   # params=args,
                                   data=args)
        return self._resp_json(request)

    def order_canceltips(self, **kwargs):
        """
        获取取消订单提示
        """
        args = {}
        args.update(**kwargs)
        request = requests.Request(method='GET',
                                   url=self._order_canceltips_url,
                                   params=args)
        return self._resp_json(request)

    def order_payment_callback(self, **kwargs):
        """
        订单支付回调
        """
        args = {}
        args.update(**kwargs)
        request = requests.Request(method='POST',
                                   url=self._order_payment_callback_url,
                                   # params=args,
                                   data=args)
        return self._resp_json(request)


if __name__ == '__main__':
    gds_client = GDSClient()
    res = gds_client.region_list()
    print res
